import React from 'react';
import { Link } from 'react-router-dom';
import { ArrowRight, Code, Palette, Download, Book, Star, Users, Zap, Eye, Play, FileText, Copy, Check, ChevronLeft, ChevronRight } from 'lucide-react';
import { templates } from '../../data/chartTemplates';
import Tooltip from '../components/Tooltip';
import Editor from '@monaco-editor/react';
import mermaid from 'mermaid';
import './HomePage.css';

// Monaco Editor configuration for Mermaid language
const defineMermaidLanguage = (monaco) => {
  monaco.languages.register({ id: 'mermaid' });
  
  monaco.languages.setMonarchTokensProvider('mermaid', {
    tokenizer: {
      root: [
        [/(flowchart|sequenceDiagram|classDiagram|stateDiagram|erDiagram|gantt|pie|graph|journey|requirementDiagram|gitGraph|C4Context|C4Container|C4Component|C4Deployment|mindmap|timeline|title|section|subgraph|end|direction|TB|BT|RL|LR|TD)\b/, 'keyword'],
        [/(participant|actor|activate|deactivate|destroy|create|alt|opt|loop|par|critical|break|rect|link|over|left of|right of|links|note|autonumber|accTitle|accDescription)\b/, 'sequence-specific'],
        [/(class|interface|enum|abstract|static|public|private|protected|package|annotation|classDef)\b/, 'class-specific'],
        [/(state|stateDiagram-v2|as|entry|exit|do|history|deep history|final)\b/, 'state-specific'],
        [/(entity|relationship|one to one|one to many|many to one|many to many|table|column|primary key|foreign key|index|constraint)\b/, 'er-specific'],
        [/(dateFormat|axisFormat|todayMarker|tickInterval|excludes|includes|task|milestone|crit|done|after|before|id)\b/, 'gantt-specific'],
        [/(requirement|element|relationship|type|text|risk|verifyMethod)\b/, 'requirement-specific'],
        [/(commit|branch|checkout|merge|cherry-pick|rebase|reset|tag|HEAD|master|main|develop|feature|release|hotfix)\b/, 'git-specific'],
        [/(style|click|call|callback|href|callURL|clickURL|linkStyle)\b/, 'function'],
        [/(config|init|theme|themeVariables|securityLevel)\b/, 'type'],
        [/%%.*/, 'comment'],
        [/#.*/, 'comment'],
        [/-->/, 'string'],
        [/--/, 'string'],
        [/->>/, 'string'],
        [/->/, 'string'],
        [/-/, 'string'],
        [/<-->/, 'string'],
        [/<--/, 'string'],
        [/<</, 'string'],
        [/<-/, 'string'],
        [/\d+/, 'number'],
        [/\w+/, 'identifier']
      ]
    }
  });
  
  // Define theme colors for Mermaid language (light theme)
  monaco.editor.defineTheme('mermaid-light', {
    base: 'vs',
    inherit: true,
    rules: [
      { token: 'keyword', foreground: '#0000FF', fontStyle: 'bold' },
      { token: 'function', foreground: '#008000', fontStyle: 'bold' },
      { token: 'sequence-specific', foreground: '#DC143C', fontStyle: 'bold' },
      { token: 'class-specific', foreground: '#006400', fontStyle: 'bold' },
      { token: 'state-specific', foreground: '#008B8B', fontStyle: 'bold' },
      { token: 'er-specific', foreground: '#8B008B', fontStyle: 'bold' },
      { token: 'gantt-specific', foreground: '#8B4513', fontStyle: 'bold' },
      { token: 'requirement-specific', foreground: '#FF69B4', fontStyle: 'bold' },
      { token: 'git-specific', foreground: '#FF8C00', fontStyle: 'bold' },
      { token: 'type', foreground: '#800080', fontStyle: 'bold' },
      { token: 'comment', foreground: '#808080', fontStyle: 'italic' },
      { token: 'string', foreground: '#FF8C00', fontStyle: 'bold' },
      { token: 'string.escape', foreground: '#FF6347', fontStyle: 'bold' },
      { token: 'string.invalid', foreground: '#FF0000', fontStyle: 'italic' },
      { token: 'delimiter', foreground: '#383838', fontStyle: 'bold' },
      { token: 'bracket-content', foreground: '#00008B', fontStyle: 'bold' },
      { token: 'brace-content', foreground: '#00008B', fontStyle: 'bold' },
      { token: 'number', foreground: '#008080', fontStyle: 'bold' },
      { token: 'identifier', foreground: '#000000' }
    ],
    colors: {
      'editor.background': '#ffffff',
      'editor.foreground': '#1F2937',
      'editor.lineHighlightBackground': '#f3f4f6',
      'editor.selectionBackground': '#dbeafe',
      'editor.selectionForeground': '#1F2937',
      'editor.inactiveSelectionBackground': '#dbeafe'
    }
  });
};

const HomePage = () => {
  const [activeChart, setActiveChart] = React.useState('flowchart');
  const [currentCode, setCurrentCode] = React.useState(templates.flowchart);
  const [copied, setCopied] = React.useState(false);
  const [scrollProgress, setScrollProgress] = React.useState(0);
  const [isScrolled, setIsScrolled] = React.useState(false);
  const [chartZoom, setChartZoom] = React.useState(1);
  const [isFullscreen, setIsFullscreen] = React.useState(false);
  const chartSelectorRef = React.useRef(null);
  const chartPreviewRef = React.useRef(null);

  // Initialize mermaid
  React.useEffect(() => {
    mermaid.initialize({
      startOnLoad: false,
      theme: 'default',
      securityLevel: 'loose',
      flowchart: {
        useMaxWidth: true,
        htmlLabels: true
      },
      sequence: {
        diagramMarginX: 50,
        diagramMarginY: 10,
        actorMargin: 50,
        width: 150,
        height: 65,
        boxMargin: 10,
        boxTextMargin: 5,
        noteMargin: 10,
        messageMargin: 35
      }
    });
  }, []);
  const features = [
    {
      icon: Code,
      title: '实时编辑',
      description: '支持 Monaco Editor 的代码编辑器，提供语法高亮和智能提示',
      color: '#4CAF50'
    },
    {
      icon: Palette,
      title: '主题定制',
      description: '8种预设主题 + 自定义主题，支持实时预览和颜色配置',
      color: '#9C27B0'
    },
    {
      icon: Download,
      title: '导出功能',
      description: '支持 PNG、SVG 格式导出，可自定义背景色和图案',
      color: '#2196F3'
    },
    {
      icon: Book,
      title: '完整文档',
      description: '详细的语法文档和使用指南，包含丰富的示例代码',
      color: '#FF9800'
    },
    {
      icon: Eye,
      title: '实时预览',
      description: '代码变更即时渲染，支持缩放、拖拽和迷你地图',
      color: '#F44336'
    },
    {
      icon: Zap,
      title: '性能优化',
      description: '快速渲染引擎，支持大型图表的流畅编辑',
      color: '#00BCD4'
    }
  ];



  const handleChartTypeChange = (chartId, template) => {
    setActiveChart(chartId);
    setCurrentCode(template);
  };

  // 视差滚动效果已取消
  // Parallax scroll effect removed

  const copyCode = async () => {
    try {
      await navigator.clipboard.writeText(currentCode);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (err) {
      console.error('复制失败:', err);
    }
  };

  const scrollLeft = () => {
    if (chartSelectorRef.current) {
      chartSelectorRef.current.scrollBy({ left: -200, behavior: 'smooth' });
    }
  };

  const scrollRight = () => {
    if (chartSelectorRef.current) {
      chartSelectorRef.current.scrollBy({ left: 200, behavior: 'smooth' });
    }
  };

  // 图表控制功能
  const navigateToEditor = () => {
    // 将当前代码保存到localStorage，然后跳转到编辑器页面
    localStorage.setItem('mermaid_code', currentCode);
    localStorage.setItem('mermaid_chart_type', activeChart);
    window.location.href = '/editor';
  };

  const zoomIn = () => {
    const newZoom = Math.min(chartZoom + 0.1, 2);
    setChartZoom(newZoom);
    
    // 当缩放超过1.5倍时，自动进入全屏模式
    if (newZoom > 1.5 && !isFullscreen) {
      enterFullscreen();
    }
  };

  const zoomOut = () => {
    const newZoom = Math.max(chartZoom - 0.1, 0.5);
    setChartZoom(newZoom);
    
    // 当缩放小于等于1.5倍且当前在全屏模式时，退出全屏
    if (newZoom <= 1.5 && isFullscreen) {
      exitFullscreen();
    }
  };

  const enterFullscreen = () => {
    setIsFullscreen(true);
    // 添加全屏样式类
    document.body.classList.add('fullscreen-mode');
  };

  const exitFullscreen = () => {
    setIsFullscreen(false);
    // 移除全屏样式类
    document.body.classList.remove('fullscreen-mode');
    // 重置缩放
    setChartZoom(1);
  };

  const handleEditorBeforeMount = (monaco) => {
    defineMermaidLanguage(monaco);
  };

  const handleEditorChange = (value) => {
    setCurrentCode(value || '');
  };

  // Render chart preview
  const renderChart = React.useCallback(async () => {
    if (!chartPreviewRef.current || !currentCode.trim()) return;

    try {
      // Clear previous chart
      chartPreviewRef.current.innerHTML = '';
      
      // Generate unique ID for the chart
      const chartId = `mermaid-chart-${Date.now()}`;
      
      // Render the chart
      const { svg } = await mermaid.render(chartId, currentCode);
      
      // Insert the SVG
      chartPreviewRef.current.innerHTML = svg;
      
      // Add some styling to make it look better
      const svgElement = chartPreviewRef.current.querySelector('svg');
      if (svgElement) {
        svgElement.style.maxWidth = '100%';
        svgElement.style.height = 'auto';
        svgElement.style.transform = `scale(${chartZoom})`;
        svgElement.style.transformOrigin = 'center center';
        svgElement.style.transition = 'transform 0.3s ease';
      }
    } catch (error) {
      console.error('Error rendering chart:', error);
      chartPreviewRef.current.innerHTML = `
        <div class="chart-error">
          <Eye size={32} />
          <p>图表渲染失败</p>
          <small>${error.message}</small>
        </div>
      `;
    }
  }, [currentCode]);

  // 滚动监听和进度计算
  React.useEffect(() => {
    const handleScroll = () => {
      const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
      const scrollHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight;
      const progress = Math.min((scrollTop / scrollHeight) * 100, 100);
      
      setScrollProgress(progress);
      setIsScrolled(scrollTop > 50);
    };

    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  // Render chart when code changes
  React.useEffect(() => {
    renderChart();
  }, [renderChart]);

  

  // 锚点滚动功能
  const scrollToSection = (sectionId) => {
    const element = document.getElementById(sectionId);
    if (element) {
      element.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  };

  // 导航栏滚动效果
  React.useEffect(() => {
    const handleNavScroll = () => {
      const nav = document.querySelector('.main-nav');
      if (nav) {
        if (window.scrollY > 100) {
          nav.classList.add('scrolled');
        } else {
          nav.classList.remove('scrolled');
        }
      }
    };

    window.addEventListener('scroll', handleNavScroll, { passive: true });
    return () => window.removeEventListener('scroll', handleNavScroll);
  }, []);

  const stats = [
    { label: '图表类型', value: '14+', icon: FileText },
    { label: '主题数量', value: '8+', icon: Palette },
    { label: '模板数量', value: '80+', icon: Code },
    { label: '导出格式', value: '3种', icon: Download }
  ];

  return (
    <div className="home-page">
      {/* 滚动进度条 */}
      <div className="scroll-progress-bar" style={{ width: `${scrollProgress}%` }}></div>
      
      {/* 主导航和Hero区域整合 */}
      <div className="hero-header-section">
        <nav className="main-nav-home">
          <div className="nav-container">
            <Link to="/" className="nav-logo">
              <Code size={24} />
              <span>Mermaid Editor</span>
            </Link>

            <div className="nav-links">
              <button className="nav-link" onClick={() => scrollToSection('demo-section')}>图表演示</button>
              <button className="nav-link" onClick={() => scrollToSection('features-section')}>功能特性</button>
              <Link to="/editor" className="nav-link">开始编辑</Link>
            </div>
          </div>
        </nav>
 
        {/* Hero Section */}
        <section className="hero-section">
        <div className="hero-content">
          <div className="hero-text-content">
            <div className="hero-badge">
              <Zap size={16} />
              <span>现代化图表编辑器</span>
            </div>
            
            <h1 className="hero-title">
              Mermaid 图表
              <span className="gradient-text">编辑器</span>
            </h1>
            
            <p className="hero-description">
              基于 Web 的 Mermaid 图表编辑工具，支持多种专业图表类型。
              提供实时预览、主题定制、代码高亮等强大功能，让图表创建变得简单高效。
            </p>
            
            <div className="hero-actions">
              <Link to="/editor" className="btn btn-primary btn-large">
                <Play size={20} />
                开始创建
                <ArrowRight size={16} />
              </Link>
              
              <button 
                className="btn btn-secondary btn-large"
                onClick={() => scrollToSection('demo-section')}
              >
                <Eye size={20} />
                查看演示
              </button>
              
              <Link to="/docs" className="btn btn-outline btn-large">
                <Book size={20} />
                文档中心
              </Link>
            </div>

            <div className="hero-stats">
              {stats.map((stat, index) => {
                const IconComponent = stat.icon;
                return (
                  <div key={index} className="stat-item">
                    <div className="stat-icon">
                      <IconComponent size={20} />
                    </div>
                    <div className="stat-content">
                      <div className="stat-value">{stat.value}</div>
                      <div className="stat-label">{stat.label}</div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          <div className="hero-preview">
            <div className="preview-window">
              <div className="window-header">
                <div className="window-controls">
                  <div className="control close"></div>
                  <div className="control minimize"></div>
                  <div className="control maximize"></div>
                </div>
                <div className="window-title">示例图表</div>
              </div>
              <div className="preview-content">
                <pre className="preview-code">{templates.flowchart}</pre>
                <div className="preview-result">
                  <div className="result-placeholder">
                    <Eye size={48} />
                    <p>实时预览</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
      </div> {/* 关闭 hero-header-section */}

      {/* Demo Section */}
      <section className="demo-section section" id="demo-section">
        <div className="section-content">
          <div className="section-header">
            <h2 className="section-title">图表演示</h2>
            <p className="section-description">
              专业图表编辑工具，满足各种可视化需求
            </p>
          </div>

          <div className="chart-selector-container">
            <button className="scroll-btn scroll-left" onClick={scrollLeft}>
              <ChevronLeft size={20} />
            </button>
            <div className="chart-selector" ref={chartSelectorRef}>
              <button 
                className={`chart-type-btn ${activeChart === 'flowchart' ? 'active' : ''}`}
                onClick={() => handleChartTypeChange('flowchart', templates.flowchart)}
              >
                流程图
              </button>
              <button 
                className={`chart-type-btn ${activeChart === 'sequence' ? 'active' : ''}`}
                onClick={() => handleChartTypeChange('sequence', templates.sequence)}
              >
                时序图
              </button>
              <button 
                className={`chart-type-btn ${activeChart === 'class' ? 'active' : ''}`}
                onClick={() => handleChartTypeChange('class', templates.class)}
              >
                类图
              </button>
              <button 
                className={`chart-type-btn ${activeChart === 'state' ? 'active' : ''}`}
                onClick={() => handleChartTypeChange('state', templates.state)}
              >
                状态图
              </button>
              <button 
                className={`chart-type-btn ${activeChart === 'er' ? 'active' : ''}`}
                onClick={() => handleChartTypeChange('er', templates.er)}
              >
                ER图
              </button>
              <button 
                className={`chart-type-btn ${activeChart === 'gantt' ? 'active' : ''}`}
                onClick={() => handleChartTypeChange('gantt', templates.gantt)}
              >
                甘特图
              </button>
              <button 
                className={`chart-type-btn ${activeChart === 'pie' ? 'active' : ''}`}
                onClick={() => handleChartTypeChange('pie', templates.pie)}
              >
                饼图
              </button>
              <button 
                className={`chart-type-btn ${activeChart === 'journey' ? 'active' : ''}`}
                onClick={() => handleChartTypeChange('journey', templates.journey)}
              >
                用户旅程
              </button>
              <button 
                className={`chart-type-btn ${activeChart === 'requirement' ? 'active' : ''}`}
                onClick={() => handleChartTypeChange('requirement', templates.requirement)}
              >
                需求图
              </button>
              <button 
                className={`chart-type-btn ${activeChart === 'git' ? 'active' : ''}`}
                onClick={() => handleChartTypeChange('git', templates.git)}
              >
                Git图
              </button>
              <button 
                className={`chart-type-btn ${activeChart === 'mindmap' ? 'active' : ''}`}
                onClick={() => handleChartTypeChange('mindmap', templates.mindmap)}
              >
                思维导图
              </button>
              <button 
                className={`chart-type-btn ${activeChart === 'timeline' ? 'active' : ''}`}
                onClick={() => handleChartTypeChange('timeline', templates.timeline)}
              >
                时间线
              </button>
              <button 
                className={`chart-type-btn ${activeChart === 'c4context' ? 'active' : ''}`}
                onClick={() => handleChartTypeChange('c4context', templates.c4context)}
              >
                C4图
              </button>
              <button 
                className={`chart-type-btn ${activeChart === 'quadrant' ? 'active' : ''}`}
                onClick={() => handleChartTypeChange('quadrant', templates.quadrant)}
              >
                四象限图
              </button>
            </div>
            <button className="scroll-btn scroll-right" onClick={scrollRight}>
              <ChevronRight size={20} />
            </button>
          </div>

          <div className="chart-display-container">
            <div className="code-panel">
              <div className="panel-header">
                <h3>图表代码</h3>
                <div className="zoom-controls">
                  <button className={`zoom-button ${copied ? 'copied' : ''}`} onClick={copyCode} title="复制代码">
                    {copied ? <Check size={16} /> : <Copy size={16} />}
                  </button>
                  <button className="zoom-button" onClick={navigateToEditor} title="跳转到编辑页面">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
                      <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>
                      <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>
                    </svg>
                  </button>
                </div>
              </div>
              <div className="code-content-wrapper">
                <Editor
                  height="400px"
                  language="mermaid"
                  theme="mermaid-light"
                  value={currentCode}
                  onChange={handleEditorChange}
                  beforeMount={handleEditorBeforeMount}
                  options={{
                    readOnly: false,
                    minimap: { enabled: false },
                    scrollBeyondLastLine: false,
                    fontSize: 14,
                    lineNumbers: 'on',
                    wordWrap: 'on',
                    automaticLayout: true,
                    folding: true,
                    renderLineHighlight: 'line',
                    selectOnLineNumbers: true,
                    matchBrackets: 'always',
                    autoClosingBrackets: 'always',
                    autoIndent: 'full',
                    formatOnPaste: true,
                    formatOnType: true,
                    bracketPairColorization: { enabled: true },
                    guides: {
                      bracketPairs: true,
                      indentation: true
                    }
                  }}
                />
              </div>
            </div>

            <div className="preview-panel">
              <div className="panel-header">
                <h3>图表预览</h3>
                <div className="zoom-controls">
                  <button className="zoom-button" onClick={zoomOut} title="缩小图表" disabled={chartZoom <= 0.5}>
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
                      <circle cx="12" cy="12" r="10"></circle>
                      <line x1="8" y1="12" x2="16" y2="12"></line>
                    </svg>
                  </button>
                  <button className="zoom-button" onClick={zoomIn} title="放大图表" disabled={chartZoom >= 2}>
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
                      <circle cx="12" cy="12" r="10"></circle>
                      <line x1="8" y1="12" x2="16" y2="12"></line>
                      <line x1="12" y1="8" x2="12" y2="16"></line>
                    </svg>
                  </button>
                  {isFullscreen && (
                    <button className="zoom-button" onClick={exitFullscreen} title="退出全屏">
                      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
                        <line x1="18" y1="6" x2="6" y2="18"></line>
                        <line x1="6" y1="6" x2="18" y2="18"></line>
                      </svg>
                    </button>
                  )}
                </div>
              </div>
              <div className="chart-preview-container">
                <div className="chart-preview" ref={chartPreviewRef}>
                  <div className="chart-placeholder">
                    <Eye size={64} />
                    <p>图表预览区域</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Features Section */}
      <section className="features-section section" id="features-section">
        <div className="section-content">
          <div className="section-header">
            <h2 className="section-title">强大功能</h2>
            <p className="section-description">
              专业的图表编辑体验，满足各种可视化需求
            </p>
          </div>

          <div className="features-grid">
            {features.map((feature, index) => {
              const IconComponent = feature.icon;
              return (
                <div key={index} className="feature-card">
                  <div className="feature-icon" style={{ backgroundColor: `${feature.color}20`, color: feature.color }}>
                    <IconComponent size={24} />
                  </div>
                  <h3 className="feature-title">{feature.title}</h3>
                  <p className="feature-description">{feature.description}</p>
                </div>
              );
            })}
          </div>
        </div>
      </section>



      {/* CTA Section */}
      <section className="cta-section section">
        <div className="section-content">
          <div className="section-header">
            <h2 className="section-title">开始创建你的第一个图表</h2>
            <p className="section-description">
              无需安装任何软件，直接在浏览器中使用强大的 Mermaid 图表编辑器
            </p>
          </div>
          
          <div className="cta-actions">
            <Link to="/editor" className="btn btn-primary btn-large">
              <Play size={20} />
              立即开始
              <ArrowRight size={16} />
            </Link>
          </div>
        </div>
      </section>

      {/* Footer */}
      <footer className="footer">
        <div className="footer-content">
          <div className="footer-section">
            <h3 className="footer-title">Mermaid 图表编辑器</h3>
            <p className="footer-description">
              基于 Web 的现代化 Mermaid 图表编辑工具
            </p>
          </div>
          
          <div className="footer-section">
            <h4 className="footer-heading">功能</h4>
            <ul className="footer-links">
              <li><Link to="/editor">图表编辑器</Link></li>
              <li><Link to="/docs">文档中心</Link></li>
              <li><Link to="/templates">模板库</Link></li>
            </ul>
          </div>
          
          <div className="footer-section">
            <h4 className="footer-heading">资源</h4>
            <ul className="footer-links">
              <li><a href="https://mermaid.js.org/" target="_blank" rel="noopener noreferrer">Mermaid 官网</a></li>
              <li><a href="https://mermaid.js.org/syntax/syntax.html" target="_blank" rel="noopener noreferrer">语法文档</a></li>
            </ul>
          </div>
        </div>
        
        <div className="footer-bottom">
          <p>&copy; 2025 ACE Mermaid 图表编辑器. 基于 Mermaid.js 构建.</p>
        </div>
      </footer>
    </div>
  );
};

export default HomePage;